<template>
    <a-drawer popup-container="#wrap" width="100%" :visible="show" :ok-loading="form.loading" @cancel="show = false"
        @ok="submit">
        <template #title>
            {{ $t('components.draw.60zei71el000') }}
        </template>
        <div class="draw">
            <div id="draw"></div>
        </div>
    </a-drawer>
</template>

<script lang='ts' setup>
import { defineModel } from 'vue'
import {
    // GeometryLayer,
    Scene,
    PointLayer
    // , LineLayer
} from '@antv/l7';
import { ControlEvent, DrawControl } from '@antv/l7-draw';
import { GaodeMap } from '@antv/l7-maps';
import { apiRiskUpdate } from '@/api/risk'
const drawPoint = ref([]);
const show = defineModel('show', { default: false })
// const list: any = defineModel('list', { default: [] })
const detail = defineModel('data', {
    default: {
        points: [],
        point: '',
        color: ''
    } as any
})
const local = useLocal()
const emit = defineEmits(['refresh'])
const form = reactive({
    loading: false,
    uid: local.usermsg.id
})
const scene = ref();
const locationLayer = ref();
const mounted = ref(false)
const toCenter = () => {
    let [lng, lat] = detail.value?.point?.split(',')
    scene.value.panTo([lng, lat]);
}
let color = {
    normal: {
        color: '#6F17FF',
    },
    hover: {
        color: '#6F17FF',
    },
    active: {
        color: '#6F17FF'
    },
    text: {
        color: '#6F17FF'
    }
}
const style = {
    // point: {
    //     ...color
    // },
    // line: {
    //     ...color
    // },
    polygon: {
        ...color
    },
    // midPoint: {
    //     ...color
    // },
    // dashLine: {
    //     ...color
    // },
}
let drawControl: any = null
const createControl = () => {

    drawControl = new DrawControl(scene.value, {
        drawConfig: {
            // 支持设置展示的绘制按钮，并传入绘制类实例化时的 options
            polygon: {
                initialData: detail.value?.points?.length ? [
                    {
                        type: 'Feature',
                        properties: {},
                        geometry: {
                            type: 'Polygon',
                            coordinates: [
                                detail.value?.points?.map((item: any) => {
                                    return [item.lng, item.lat]
                                })
                            ],
                        },
                    },
                ] : [],
                distanceOptions: {},
                areaOptions: {},
                maxCount: 1,
                style: {
                    ...style
                },
            },
            circle: {
                // initialData:detail.value?.points?.length ? [
                // {
                //     type: 'Feature',
                //     properties: {},
                //     geometry: {
                //     type: 'Circle',
                //     coordinates: [
                //         detail.value?.points?.map((item: any) => {
                //             return [item.lng, item.lat]
                //         })
                //     ],
                //     },
                // },
                // ] : [],
                distanceOptions: {},
                areaOptions: {},
                maxCount: 1,
                style: {
                    ...style
                },
            },
            clear: {},
        }
    }
    );

    drawControl.on(ControlEvent.DataChange, (newData: any) => {
        // console.log(newData)
        if (newData?.polygon?.length) {
            return drawPoint.value = newData?.polygon[0]?.geometry?.coordinates[0]
        } else if (newData?.circle?.length) {
            return drawPoint.value = newData?.circle[0]?.geometry?.coordinates[0]
        }
        return drawPoint.value = []
    });
    scene.value.addControl(drawControl);
}
(window as any)._AMapSecurityConfig = {
    securityJsCode: 'd84d8285ac6711fc36f6b313ab21372c'
}
const init = () => {
    let [lng, lat] = detail.value?.point?.split(',')
    scene.value = new Scene({
        id: 'draw',
        map: new GaodeMap({
            center: [Number(lng), Number(lat)],
            zoom: 10,
            style: local.theme == 'light' ? 'normal' : local.theme,
            token: 'bd7d25df22d89905e5257e575709c2cc',
        }),
        logoVisible: false
    });
    scene.value.on('loaded', () => {
        createControl()
        if (detail.value) {
            createLocationLayer()
        }
    });
    scene.value.addImage(
        '00',
        '/location.svg',
    );
}
//区域定位操作
const createLocationLayer = () => {
    let [lng, lat] = detail.value?.point?.split(',')
    locationLayer.value = new PointLayer({
        zIndex: 8,
    }).source(
        [
            {
                lng: Number(lng),
                lat: Number(lat),
            },
        ],
        {
            parser: {
                type: 'json',
                x: 'lng',
                y: 'lat',
            },
        },
    )
        .shape('00')
        .size(20);
    scene.value.addLayer(locationLayer.value)
}
// const imageLayerText = new PointLayer()
//     .source(data, {
//         parser: {
//             type: 'json',
//             x: 'longitude',
//             y: 'latitude',
//         },
//     })
//     .shape('name', 'text')
//     .color('#f00')
//     .size(25)
//     .style({
//         textOffset: [0, 20],
//     });
// scene.addLayer(imageLayerText);
const submit = async () => {
    if (!drawPoint.value?.length) return useMessage.warning(t('components.draw.60zei71eolw0'));
    form.loading = true
    const { code } = await apiRiskUpdate({
        ...detail.value,
        points: drawPoint.value.map(item => {
            return {
                lng: item[0],
                lat: item[1]
            }
        })
    })
    // console.log(drawPoint.value)
    form.loading = false
    if (code != 200) return
    show.value = false
    emit('refresh')

}
useWatch(show, (val: boolean) => {
    if(!detail.value?.point) return;
    if (val) {
        if (!mounted.value) {
            mounted.value = true
            init()
        } else {
            toCenter()
            createControl()
            createLocationLayer()
        }
    } else {
        scene.value?.removeControl(drawControl)
        drawControl.value = null
        locationLayer.value && scene.value?.removeLayer(locationLayer.value);
        locationLayer.value = null
    }
})
onBeforeUnmount(() => {
    scene.value?.destroy()
})
</script>

<style lang="less" scoped>
.draw {
    width: 100%;
    height: 100%;

    #draw {
        position: relative;
        width: 100%;
        height: 100%;
        border-radius: 5px;
        overflow: hidden;
    }
}
</style>